package com.atguigu.security.filter;

import com.atguigu.common.result.Result;
import com.atguigu.common.result.ResultCodeEnum;
import com.atguigu.common.utils.JacksonUtils;
import com.atguigu.common.utils.JwtUtils;
import com.atguigu.security.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 认证解析过滤器
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private RedisTemplate redisTemplate;

    public TokenAuthenticationFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        Object captcha = request.getSession().getAttribute("captcha");
        System.out.println("captcha:" + captcha);


        logger.info("uri:" + request.getRequestURI());
        //如果是登录接口，直接放行
        if ("/service-system/admin/login".equals(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }

        if ("/prod-api/admin/login".equals(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if (null != authentication) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } else {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.PERMISSION));
        }
    }

    /**
     * 从redis取出用户权限，验证访问权限
     *
     * @param request
     * @return
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token置于header里
        String token = request.getHeader("token");
        logger.info("token:" + token);
        if (!StringUtils.isEmpty(token)) {
            String username = JwtUtils.getUsername(token);
            logger.info("username:" + username);
            if (!StringUtils.isEmpty(username)) {
                String userStr = (String) redisTemplate.opsForValue().get(username);
                Map tokenObj = JacksonUtils.string2Obj(userStr, Map.class);
                List mapList = (List) tokenObj.get("authorities");
                Object sysUser = tokenObj.get("sysUser");
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                for (Object object : mapList) {
                    Map map = (Map) object;
                    authorities.add(new SimpleGrantedAuthority((String) map.get("authority")));
                }
                return new UsernamePasswordAuthenticationToken(sysUser, null, authorities);
            }
        }
        return null;
    }
}
